package com.ng.common.exception;

import com.ng.common.constant.MessageConstant;
import com.ng.common.result.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 * - 处理项目中抛出的业务异常
 *
 * @author Ng
 * @date 2024/03/08
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param exception 异常
     * @return Result 统一响应结果
     */
    @ExceptionHandler
    public R<String> exceptionHandler(BaseException exception) {

        // 拦截到错误
        return R.error(exception.getMessage());
    }

    /**
     * 处理 SQL 错误
     * @param exception 异常
     * @return 统一响应结果
     */
    @ExceptionHandler
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {

        String message = exception.getMessage();
        if (message.contains("Duplicate entry")) {
            // 将获取到的错误信息按照空格分割
            // Duplicate entry 'xxx' for key 'user.idx_username'
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ACCOUNT_ALREADY_EXISTS;
            return R.error(msg);
        } else {
            return R.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
